import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @description RiLi
 * @author 何文俊
 * @date 2023-12-06
 */
@Slf4j
@Service
public class RiLiServiceImpl implements RiLiService {

    @Resource
    private RiLiMapper riLiMapper;

    @Override
    public ReturnT update(String holiday, String type, String dept) {
        if (holiday == null || holiday.trim().isEmpty()) {
            // 返回错误消息，如果holiday为空或无效
            return new ReturnT(400,"日期无效");
        }
        if (!type.equalsIgnoreCase("set") && !type.equalsIgnoreCase("delete")) {
            // 返回错误消息，如果type不是有效的操作类型
            return new ReturnT(400,"更新类型无效");
        }

        RiLi r = new RiLi();
        String[] holi = holiday.split("-");
        r.setYearMonth(holi[0]+"-"+holi[1]); //年月间加-为了加载数据时方便拼接
        r.setDept(dept);
        RiLi rr = riLiMapper.getByYearMonthAndDept(r);

        if (type.equalsIgnoreCase("set")) {
            if (rr == null) {
                r.setHolidays(holi[2]);
                int c = riLiMapper.insert(r);
                return c>0? ReturnT.success("更新成功"): ReturnT.error("更新失败");
            } else {
                rr.setHolidays(StringUtils.isBlank(rr.getHolidays())?holi[2] : rr.getHolidays() + "," + holi[2]); //如果当前月份的休息日都被删除了 值就变成了空，这时候再添加休息日时就不需要在前面加 ，了 ，否则就需要在新日期之前加逗号分隔
                return riLiMapper.update(rr)? ReturnT.success("更新成功") :  ReturnT.error("更新失败");
            }
        } else if (type.equalsIgnoreCase("delete")) {
            String [] holidayArray =  rr.getHolidays().split(",");
            ArrayList<String> holidayArrayList = new ArrayList<>(Arrays.asList(holidayArray));
            holidayArrayList.removeIf(s -> s.equals(holi[2])); //如果有这个日期就删除，如果没有不会报错
            String result = String.join(",", holidayArrayList);// 转化回以逗号分隔的字符串
            rr.setHolidays(result);
            return riLiMapper.update(rr)? ReturnT.success("更新成功") :  ReturnT.error("更新失败");
        }else{
            return new ReturnT(400, "操作不合法");
        }
    }

    @Override
    public RiLi getByYearMonthAndDept(RiLi riLi) {
        return riLiMapper.getByYearMonthAndDept(riLi);
    }
}